package warehouse;

import java.util.LinkedList;
import java.util.Map;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author Razvan
 */
public class ColumnTree {

    TableNode root;
    Map<String, TableNode> nodeMap;

    public ColumnTree(String rootTable, Map<String, TableNode> nodeMap) {
        this.root = nodeMap.get(rootTable);
        this.nodeMap = nodeMap;
    }

    @Override
    public String toString() {
        final StringBuilder buf = new StringBuilder();
        LinkedList<TableNode> que = new LinkedList<TableNode>();
        que.add(root);
        //int indent = 0, i;
        int level = 0, counter = 1;
        while (que.size() != 0) {
            TableNode t = que.pop();
            counter--;

            if (counter <= 0) {
                level++;
                counter = que.size();
            }

            que.addAll(t.children); // System.out.println("T "+t.tableName+ " children "+t.children.size());
            //for(i=0; i<=indent; i++) buf.append("\t");
            buf.append(" Tabel ");
            buf.append(t.tableName);
            buf.append(" nivel [" + level + "] \n");
            //for(i=0; i<=indent; i++) buf.append("\t");
            buf.append("Coloane non-unice ");
            buf.append(t.columnNamesQueryMap.keySet());

            buf.append("\n\n");
        }
        return buf.toString();
    }

    public String toJson() throws JSONException {
        final JSONObject object = new JSONObject();
        object.put("name", root.tableName);

        final JSONArray children = new JSONArray();
        object.put("children", children);
        toJson(children, root);
        return object.toString();
    }

    private void toJson(final JSONArray parent, final TableNode parentTree) throws JSONException {
        final JSONObject curObject = new JSONObject();
        curObject.put("name", parentTree.tableName);
        final JSONArray children = new JSONArray();
        curObject.put("children", children);

        if (parentTree.children != null && !parentTree.children.isEmpty()) {
            for (TableNode t : parentTree.children) {
                toJson(children, t);
            }
        }

        for (String column : parentTree.columnNamesQueryMap.keySet()) {
            final JSONObject columnEntry = new JSONObject();
            columnEntry.put("name", column);
            columnEntry.put("size", parentTree.columnNamesQueryMap.get(column));
            //columnEntry.put("size", 10);
            children.put(columnEntry);
        }

        parent.put(curObject);
    }
}
